import { throttle } from 'shiptools'
import { getNationalitiesApi } from '../../api/index'
import { uniq, setPage } from '../../utils/index'
import { TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
const pageName = TRACER_PAGES['nations']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyword: '',
    list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getNationalities()
  },
  
  onShow: function() {
    setPage(pageName, PRODUCT_CODE)
  },

  onChange: throttle(function(e) {
    const keyword = e.detail.value
    this.getNationalities(keyword)
  }, 500),

  onActionClick: function(e) {
    this.setData({
      keyword: ''
    })

  },

  onClick: function(e) {
    const item = e.detail
    const nationalityDetail = item.name;
    const nationalityThreeCode = item.threeCode
    const nationalityTwoCode = item.twoCode
    
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('selectNationChannel', { data: {
      nationalityDetail,
      nationalityThreeCode,
      nationalityTwoCode
    } });
    wx.navigateBack();
  },


  getNationalities: function(keyword = '') {
    const that = this
    wx.showLoading({
      title: '正在加载...',
      mask: true,
      success: (result)=>{
        
      },
      fail: ()=>{},
      complete: ()=>{}
    });
    getNationalitiesApi({
      keyword
    }).then(nations => {

      let list = [];
      if(nations && nations.length) {
        let letters = nations.map(item => item.NationalFirstChar)
        letters = uniq(letters).sort()
        letters.map(letter => {
          let _nation = {
            title: letter,
            key: letter,
            items: []
          }
          nations.map(nation => {
            if(nation.NationalFirstChar === letter) {
              _nation.items.push({
                name: nation.NationalName,
                threeCode: nation.NationalThreeCode,
                twoCode: nation.NationalTwoCode
              })
            }
          })
          
          list.push(_nation)
        })
      }

      wx.hideLoading();
      that.setData({
        list
      })
    })
  },

  onBlur: function() {
    this.setData({
      keyword: ''
    })
  }

})